//
//  TVViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/15.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "TVViewController.h"
#import "TVTableViewCell.h"
#import "TVViewModel.h"
#import "MoviePlayerViewController.h"
#import "NetWork.h"
@interface TVViewController ()<UITableViewDelegate,UITableViewDataSource,MPMoviePlayerControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *tvModelArray; //tvmodel数组

@property (nonatomic, assign) int per_page; // 上下拉刷新的数据个数

@end

@implementation TVViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建tableView
    [self createTableView];
    
    // 进来就刷新
    [self downRefresh];
    
//    [self tvDownRefreshGetAsynchronousRequest];
    
    // 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    // 上拉刷新
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
}

- (NSMutableArray *)tvModelArray
{
    if (!_tvModelArray)
    {
        _tvModelArray = [[NSMutableArray alloc] init];
        self.per_page = 10; //懒加载的时候 就初始化为10
    }
    return _tvModelArray;
}

#pragma mark - 下拉刷新
- (void)downRefresh
{
//    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
//    // 如果有网
//    if ([r currentReachabilityStatus] != NotReachable)
//    {
//        [FMDBManage deleteAllTVTable];   //刷新成功后再移除数据库中数据。
//    }
//    else
//    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
//    }
    
    // 重新解析
    
    if ([[NetWork shareInstance]rechability])
    {
        [self tvDownRefreshGetAsynchronousRequest];

    }
    else
    {
        
    }
}

#pragma mark - 上拉刷新
- (void)upRefresh
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网
    if ([r currentReachabilityStatus] != NotReachable)
    {
        // 上来刷新
        [self tvupRefreshGetAsynchronousRequest];
    }
    else
    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
        // 停止刷新
        [self.tableView.footer endRefreshing];
    }
    
    
}

#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight  - 64 - 30 - 49) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; //取消线
    [self.view addSubview:_tableView];
}

#pragma mark - 设置每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tvModelArray.count;
}

#pragma mark - 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    [tableView registerClass:[TVTableViewCell class] forCellReuseIdentifier:cellIdentifier];
    TVTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    
    TVViewModel *tvModel = [self.tvModelArray objectAtIndex:indexPath.row];

    // 传入model加载数据
    [cell loadCellWithDataModel:tvModel];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 250;
}

#pragma mark - tv下拉异步解析
- (void)tvDownRefreshGetAsynchronousRequest
{
    // 创建表
    [FMDBManage createTVTable];
    NSArray *tvArray = [FMDBManage selectAllTVTable];
    
    if (tvArray.count != 0)
    {
        self.tvModelArray = [tvArray mutableCopy];
    }
    else
    {
        
        int page = 10;
        NSString *stringUrl = [NSString stringWithFormat:kTvUlr,page];
        [LORequestManger GET:stringUrl success:^(id response) {
            [self.tvModelArray removeAllObjects];
            NSDictionary *bigDictionary = (NSDictionary *)response;
            NSDictionary *smallDictionary = [bigDictionary objectForKey:@"data"];
            NSMutableArray *tvArray = [smallDictionary objectForKey:@"feeds"];
            for (NSDictionary *tvDictionary in tvArray)
            {
                TVViewModel *tvModel = [TVViewModel tvViewModelWithDictionary:tvDictionary];
                [self.tvModelArray addObject:tvModel];
       
                // 插入数据到数据库
                [FMDBManage insertTVTableTitle:tvModel.title videoTime:tvModel.video_length videoImageUrl:tvModel.feature_img];
                
            }
            [self.tableView reloadData];
            
           
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [ProgressHUD progressHUD:self.view labelText:@"加载失败,请检查网络"];
        }];
    }
    // 停止刷新
    [self.tableView.header endRefreshing];
  
}

#pragma mark - tv上拉异步解析
- (void)tvupRefreshGetAsynchronousRequest
{
    self.per_page +=10;
    NSString *stringUrl = [NSString stringWithFormat:kTvUlr,self.per_page];
    [LORequestManger GET:stringUrl success:^(id response) {
        [self.tvModelArray removeAllObjects];
        NSDictionary *bigDictionary = (NSDictionary *)response;
        NSDictionary *smallDictionary = [bigDictionary objectForKey:@"data"];
        NSMutableArray *tvArray = [smallDictionary objectForKey:@"feeds"];
        for (NSDictionary *tvDictionary in tvArray)
        {
            TVViewModel *tvModel = [TVViewModel tvViewModelWithDictionary:tvDictionary];
            [self.tvModelArray addObject:tvModel];
        }
        [self.tableView reloadData];

        // 停止刷新
        [self.tableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败,请检查网络"];
    }];
    
    // 停止刷新
    [self.tableView.footer endRefreshing];
}

#pragma - mark - 代理释放自己推出的播发器 谁申请 谁释放
- (void)moviePlayerDidFinished
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击cell触发方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MoviePlayerViewController *movieVc = [[MoviePlayerViewController alloc] init];
    movieVc.delegate = self;
    TVViewModel *tvViewModel = [self.tvModelArray objectAtIndex:indexPath.row];
    movieVc.mp4_url = tvViewModel.video_link;
    [self presentViewController:movieVc animated:YES completion:nil];
}

#pragma mark - 内容警告提示
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}


@end
